package com.linciping.plugin.action;

import com.intellij.codeInsight.CodeInsightActionHandler;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.linciping.plugin.base.BaseKotlinGenerateAction;
import com.linciping.plugin.base.SingleClassKotlinGenerateAction;
import com.linciping.plugin.writer.CodeInsertWriter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.asJava.classes.KtLightClass;
import org.jetbrains.kotlin.asJava.classes.KtUltraLightClass;
import org.jetbrains.kotlin.asJava.classes.KtUltraLightClassForFacade;
import org.jetbrains.kotlin.psi.KtClass;
import org.jetbrains.kotlin.psi.KtFile;

public class CodeInsertAction extends BaseKotlinGenerateAction {

    private Project project;

    public CodeInsertAction() {
    }

    public CodeInsertAction(CodeInsightActionHandler codeInsightActionHandler) {
        super(codeInsightActionHandler);
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        // TODO: insert action logic here
        KtFile ktFile = (KtFile) e.getData(LangDataKeys.PSI_FILE);
        project = e.getProject();
        assert project != null;
        assert ktFile != null;
        KtClass ktClass = getTargetClass(ktFile);
        if (ktClass != null) {
            ApplicationManager.getApplication().runWriteAction(() -> {
                CodeInsertWriter codeInsertWriter = new CodeInsertWriter(project, ktClass);
                CommandProcessor.getInstance().executeCommand(project, codeInsertWriter, codeInsertWriter.getClass().getSimpleName(), null);
            });
        }
    }

    protected KtClass getTargetClass(KtFile ktFile) {
        for (PsiElement psiElement : ktFile.getChildren()) {
            if (psiElement instanceof KtClass) {
                return (KtClass) psiElement;
            }
        }
        return null;
    }
}
